package sol.leetcode;

import java.util.Arrays;

/**
 * 3Sum Closest
 */
public class Issue016 {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int len = nums.length;
        int close = nums[0] + nums[1] + nums[len - 1];
        for (int p1 = 0; p1 <= len - 2; ++p1) {
            int val = nums[p1];
            int remain = target - val;
            int p2 = p1 + 1, p3 = len - 1;
            while (p2 < p3) {
                int pSum = nums[p2] + nums[p3];
                int sum = pSum + val;

                System.out.println(p1 + "=" + nums[p1] + ", " + p2 + "=" + nums[p2] + " " + p3 + "=" + nums[p3] + " sum=" + sum);

                if (pSum == remain)
                    return target;
                else
                    close = Math.abs(sum - target) < Math.abs(close - target) ? sum : close;
                if (pSum > remain)
                    p3--;
                else
                    p2++;
            }
        }
        return close;
    }

    public static void main(String[] args) {
        int[] nums = {0,1,2};
        int target = 1;
        Issue016 sol = new Issue016();
        System.out.println(sol.threeSumClosest(nums, target));
    }
}
